package org.eclipsecon.dui.interpreter.internal;

import java.util.regex.Pattern;

import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.fieldassist.ControlDecoration;

public class RegexValidator implements IValidator {

	private final String message;
	private final ControlDecoration controlDecoration;
	private Pattern pattern;

	public RegexValidator(String message, String patternString,
			ControlDecoration controlDecoration) {
		super();
		this.message = message;
		this.controlDecoration = controlDecoration;
		this.pattern = Pattern.compile(patternString); 
	}

	public IStatus validate(Object value) {
		if (value instanceof String) {
			String s = (String) value;
			if(pattern.matcher(s).matches()) {
				controlDecoration.hide();
				return Status.OK_STATUS;
			} else {
				controlDecoration.show();
				return ValidationStatus.error(message);
			}
		} else {
			throw new RuntimeException(
					"Not supposed to be called for non-strings.");
		}
	}
}
